package com.masonluo.mlonlinejudge.aspect;

import com.masonluo.mlonlinejudge.result.Result;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletResponse;

/**
 * @author masonluo
 * @date 2021/1/17 10:22 下午
 */
@Aspect
@Component
public class ControllerAspect {

    @Pointcut("@within(org.springframework.web.bind.annotation.RestController) " +
            "|| @within(org.springframework.web.bind.annotation.RestControllerAdvice)")
    public void pointCut() {
    }

    @Around("pointCut()")
    @SuppressWarnings({"uncheck", "rawtypes"})
    public Object afterReturn(ProceedingJoinPoint joinPoint) throws Throwable {
        Object ret = joinPoint.proceed();
        if (!(ret instanceof Result)) {
            return ret;
        }
        Result res = (Result) ret;
        ServletRequestAttributes attr = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attr == null) {
            throw new IllegalStateException("Not a http request");
        }
        HttpServletResponse response = attr.getResponse();
        if (response == null) {
            throw new IllegalStateException("Not a http request");
        }
        response.setStatus(res.getCode().getHttpStatus().value());
        return res;
    }
}
